// import JSEncrypt from 'jsencrypt'
import { JSEncrypt } from 'jsencrypt'
import CryptoJS from 'crypto-js'
import { Base64 } from 'js-base64'
// const Base64 = ('js-base64').Base64

// const PUBLIC_KEY =
//   'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfWgNBmqfnd1Qm90bFCwyBMn+snkgJII7MmaOFpavVNPVeAHg7zflpUxGCBkXTNpHkur9UrySy9K/uZV0EMB46ha8SDwfjwvCJi0afx2Qb7gSFl+p8EZsbwznNWb3A7yAUy6i5M9QRzS/2QrQvWPHTtvpB6oDYAWmHK+5kN40GawIDAQAB'
const PUBLIC_KEY =
  'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHo5WgbTQTkIecdC6Mb/CTcaaJs5Kcc+NWm1Fp8WUr11HZFtr7+kUmDRvcJQ4k4b3xQWSvLK3AII1c482Wi601jHAbRc7b5mtCcQUs452ViuEBYnzj6MFgm60M5XaFCg2uy/b/aqkDp0Si5yF/NOht56eL9gZxgNBA0Sf1wJzRkQIDAQAB'
// const PRIVATE_KEY =
//   'MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAISd9sxPx4GSYX9TEyudWBKUyteSqLKG0m/tpm0RZxjSYvO6CpB2v80GUtUINoOF5jeE2cqhXmiJ3un8M/I+nCCUpCX8J9kKm/1GFaxNLB5vJiim+soK+PYBcnApKYmz/MSMpCzj98xgoeXhO8DnuI7NyTAsUA3TiK0zId8rjQL/AgMBAAECgYB9CfOI8C/Lm5kR0+JfXRuNaX1XhJBKw5PmtMwWSjJK1RM3elI7o7t0NGIlOnkryTQnZLt0snGxX00ukPzpit7o/XimbileGGMDgQHAj6bNfn9Fm5UVCm2pMvufxHlXdFpj5rY09Ttq0XR/NGakLxG5xCAzRjs8h2vn9aUzFTK+AQJBAMA1lMvRU3eTu4359V/cE02iKgxfGTVhRTV+kxX7lBd5xH3tLcOJIak4eCdiyug0lkPeRhVEr7wU5q1JztOdI/cCQQC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J521MkQhQlfLspG27gQitj2HAkA/rniKZ947jn0dtM78/lco20waltUeCmR0rNns8qhfipXLH8sAfyUCm3cPvmnVZJ7iNxuJAYcux5YjRnl9etSp'
// 分段拼接符
const $splitStr = '[montage@]'
// const $splitStr = ''
// 实例化一个RSA对象
// var encrypt = new JSEncrypt()
// // 设置公钥和私钥
// encrypt.setPublicKey(PUBLIC_KEY)
// encrypt.setPrivateKey(PRIVATE_KEY)

/**
 * [rsaEncryptSet 文本加密]
 * @param  {[type]} content 待加密文本
 * JSON转换 ——> Base64转换 ——> encrypt加密（分段加密）
 */
export const rsaEncryptSet = (content) => {
  if (content == undefined) return
  let jsonContent = JSON.stringify(content) // JSON转换
  let newText = Base64.encode(jsonContent) // Base64转换
  let textEncrypt = '' //加密文本
  let maxLength = 100 //分段长度
  if (newText.length > maxLength) {
    let newArr = newText.match(/.{1,100}/g) //文本分段 数组
    for (let i = 0; i < newArr.length; i++) {
      let encryptStr = encrypt.encrypt(newArr[i]) //分段 加密
      textEncrypt = textEncrypt ? textEncrypt + $splitStr + encryptStr : encryptStr //拼接 加密字符串
    }
  } else {
    textEncrypt = encrypt.encrypt(newText) // 加密
  }
  console.log('加密：', textEncrypt)
  return textEncrypt
}
/**
 * [rsaDecryptSet 文本解密]
 * @param  {[type]} content 待解密密文
 * encrypt解密（分段解密） ——> Base64转换 ——> JSON转换
 */
export const rsaDecryptSet = (content) => {
  if (content == undefined) return
  let contentDecrypt = ''
  if (content.includes($splitStr)) {
    let newArr = content.split($splitStr) //文本分段 数组
    for (let i = 0; i < newArr.length; i++) {
      let decryptStr = encrypt.decrypt(newArr[i]) //分段 解密
      contentDecrypt += decryptStr //拼接 解密字符串
    }
  } else {
    contentDecrypt = encrypt.decrypt(content) //解密
  }
  let Base64Decrypt = Base64.decode(contentDecrypt) //Base64转换
  let decryptData = null //解密数据
  if (typeof Base64Decrypt === 'string') {
    try {
      decryptData = JSON.parse(Base64Decrypt) // JSON转换
    } catch (error) {
      decryptData = Base64Decrypt
    }
  }
  console.log('解密：', decryptData)
  return decryptData
}

/**
 * 加密方法
 * @returns {PromiseLike<ArrayBuffer>}
 * @constructor
 */
export const RSA_encryption = (jsonData: any) => {
  return jsonData;
  // let encrypt = new JSEncrypt()
  // encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + PUBLIC_KEY + '-----END PUBLIC KEY-----')
  // let encrypted = encrypt.encrypt(JSON.stringify(jsonData))
  // console.log('加密前数据:%o', jsonData)
  // console.log('加密后数据:%o', encrypted)
  // return encrypted
}
// 分段解密长字符串
const decryptLong = (obj: any, text: string) => {
  // Return the decrypted string.
  // console.log(this);
  var k = obj.getKey()
  var maxLength = (k.n.bitLength() + 7) >> 3
  try {
    var str = this.b64tohex(text)
    // var b=hex2Bytes(str);

    var inputLen = str.length

    var ct = ''

    if (inputLen > maxLength) {
      var lt = str.match(/.{1,256}/g)
      lt.forEach(function (entry) {
        var t1 = k.decrypt(entry)
        ct += t1
      })
      return ct
    }
    var y = k.decrypt(this.b64tohex(text))
    return y
  } catch (ex) {
    return false
  }
}
/**
 * 解密方法
 * @returns {PromiseLike<ArrayBuffer>}
 * "FpBBjn9YS6RdofhB74rnjl1rg6DR9415k+3BEiMOB0FrPC2yfEzUr+dM/cojZfZljFztNUj5tGuq5B7dLwAX/ODb7tTYY+TYH7G4IxGpsrd6KZ0GAeYfZWoMPWbjjmr9iJCJaoiV0z7TDD97ARi/K4E3n9e/3czduQjmffLSXJV5GSeHoqn4k3ZVIBjcIgV6ZmI0qQ0+ulUyW+CWqQTiiTl3oXyHBzOHW8n/Cs389bywJHFdQjabcoUcXJXt0vSg5Zw2+G1tet4d0779kCxaxo5ZYqVxG3n+Pi2tdteuJKRVnE8BMeh0dkdLXlU9BPW6l6biLgpSUlVHCfqAtVU1+w=="
 * @constructor
 */
export const RSA_decryption = (data: string) => {
  let encrypt = new JSEncrypt()
  encrypt.setPrivateKey(
    '-----BEGIN RSA PRIVATE KEY-----' + PRIVATE_KEY + '-----END RSA PRIVATE KEY-----',
  )
  let encrypted = encrypt.decrypt(data)
  if (encrypted == null) {
    encrypted = decryptLong(encrypt, data)
    console.log('解密前数据: 22', encrypted)
  }
  console.log('解密前数据:%o', data)
  console.log('解密后数据:%o', encrypted)
  return encrypted
}

/**
 * 日期格式化函数
 * @param date 日期对象
 * @param format 日期格式，默认为 YYYY-MM-DD HH:mm:ss
 */
export const formatDate = (date: Date, format = 'YYYY-MM-DD HH:mm:ss') => {
  // 获取年月日时分秒，通过 padStart 补 0
  const year = String(date.getFullYear())
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  // 返回格式化后的结果
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}
/**
 * 返回今天的年月日
 * @return format 日期格式，默认为 YYYY-MM-DD
 */
export const nowDate = () => {
  return formatDate(new Date(), 'YYYY-MM-DD')
}

/**
 *
 *  ---------------------------------------------------------------------------------
 *
 */

// 16进制转byte数组
function hexToBytes(hex) {
  for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16))
  return bytes
}
// byte数组转16进制
function bytesToHex(bytes) {
  for (var hex = [], i = 0; i < bytes.length; i++) {
    hex.push((bytes[i] >>> 4).toString(16))
    hex.push((bytes[i] & 0xf).toString(16))
  }
  return hex.join('')
}

JSEncrypt.prototype.encryptLong = function (string) {
  var k = this.getKey()
  try {
    var ct = '' //RSA每次加密最大117bytes，需要辅助方法判断字符串截取位置
    //1.获取字符串截取点
    var bytes = new Array()
    bytes.push(0)
    var byteNo = 0
    var len, c
    len = string.length
    var temp = 0
    for (var i = 0; i < len; i++) {
      c = string.charCodeAt(i)
      if (c >= 0x010000 && c <= 0x10ffff) {
        byteNo += 4
      } else if (c >= 0x000800 && c <= 0x00ffff) {
        byteNo += 3
      } else if (c >= 0x000080 && c <= 0x0007ff) {
        byteNo += 2
      } else {
        byteNo += 1
      }
      if (byteNo % 117 >= 114 || byteNo % 117 == 0) {
        if (byteNo - temp >= 114) {
          bytes.push(i)
          temp = byteNo
        }
      }
    }

    //2.截取字符串并分段加密
    if (bytes.length > 1) {
      for (var i = 0; i < bytes.length - 1; i++) {
        var str
        if (i == 0) {
          str = string.substring(0, bytes[i + 1] + 1)
        } else {
          str = string.substring(bytes[i] + 1, bytes[i + 1] + 1)
        }
        var t1 = k.encrypt(str)
        ct += t1
      }
      if (bytes[bytes.length - 1] != string.length - 1) {
        var lastStr = string.substring(bytes[bytes.length - 1] + 1)
        ct += k.encrypt(lastStr)
      }
      return hexToBytes(ct)
    }
    var t = k.encrypt(string)
    var y = hexToBytes(t)
    return y
  } catch (ex) {
    return false
  }
}

// utf-8数组转字符串
function utf8ByteToUnicodeStr(utf8Bytes) {
  var unicodeStr = ''
  for (var pos = 0; pos < utf8Bytes.length; ) {
    var flag = utf8Bytes[pos]
    var unicode = 0
    if (flag >>> 7 === 0) {
      unicodeStr += String.fromCharCode(utf8Bytes[pos])
      pos += 1
    } else if ((flag & 0xfc) === 0xfc) {
      unicode = (utf8Bytes[pos] & 0x3) << 30
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 24
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 18
      unicode |= (utf8Bytes[pos + 3] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 4] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 5] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 6
    } else if ((flag & 0xf8) === 0xf8) {
      unicode = (utf8Bytes[pos] & 0x7) << 24
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 18
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 3] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 4] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 5
    } else if ((flag & 0xf0) === 0xf0) {
      unicode = (utf8Bytes[pos] & 0xf) << 18
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 12
      unicode |= (utf8Bytes[pos + 2] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 3] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 4
    } else if ((flag & 0xe0) === 0xe0) {
      unicode = (utf8Bytes[pos] & 0x1f) << 12
      unicode |= (utf8Bytes[pos + 1] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 2] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 3
    } else if ((flag & 0xc0) === 0xc0) {
      //110
      unicode = (utf8Bytes[pos] & 0x3f) << 6
      unicode |= utf8Bytes[pos + 1] & 0x3f
      unicodeStr += String.fromCharCode(unicode)
      pos += 2
    } else {
      unicodeStr += String.fromCharCode(utf8Bytes[pos])
      pos += 1
    }
  }
  return unicodeStr
}

JSEncrypt.prototype.decryptLong = function (string) {
  var k = this.getKey()
  var MAX_DECRYPT_BLOCK = 128 //分段解密最大长度限制为128字节
  try {
    var ct = ''
    var t1
    var bufTmp
    var hexTmp
    var str = bytesToHex(string) //这块可能有些没有必要，因为sting参数已经及转为byte数组
    var buf = hexToBytes(str)
    var inputLen = buf.length
    //开始长度
    var offSet = 0
    //结束长度
    var endOffSet = MAX_DECRYPT_BLOCK

    //分段解密
    while (inputLen - offSet > 0) {
      if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
        bufTmp = buf.slice(offSet, endOffSet)
        hexTmp = bytesToHex(bufTmp)
        t1 = k.decrypt(hexTmp)
        ct += t1
        console.log('分段' + offSet)
        console.log(hexTmp)
        console.log(t1)
      } else {
        bufTmp = buf.slice(offSet, inputLen)
        hexTmp = bytesToHex(bufTmp)
        t1 = k.decrypt(hexTmp)
        ct += t1
        console.log('分段' + offSet)
        console.log(hexTmp)
        console.log(t1)
      }
      offSet += MAX_DECRYPT_BLOCK
      endOffSet += MAX_DECRYPT_BLOCK
    }
    return ct
  } catch (ex) {
    return false
  }
}
//

/* JSEncrypt加密 */
export const RSA_encryption1 = (params) => {
  let data = JSON.stringify(params)
  var jsencrypt = new JSEncrypt()
  console.log(jsencrypt)
  jsencrypt.setPublicKey(PUBLIC_KEY)
  var result = jsencrypt.encryptLong(data)
  console.log('加密前 888 ：', params, '加密后：', result)
  return result
}
/* JSEncrypt解密 */
export const RSA_decryption1 = (data) => {
  var jsencrypt = new JSEncrypt()
  jsencrypt.setPrivateKey(PRIVATE_KEY)
  var result = jsencrypt.decryptLong(data)
  return result
}

// md5 加密
var md5Key =
  'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCEnfbMT8eBkmF/UxMrnVgSlMrXkqiyhtJv7aZtEWcY0mLzugqQdr/NBlLVCDaDheY3hNnKoV5oid7p/DPyPpwglKQl/CfZCpv9RhWsTSwebyYopvrKCvj2AXJwKSmJs/zEjKQs4/fMYKHl4TvA57iOzckwLFAN04itMyHfK40C/wIDAQAB'
export const md5Str = (request_id:any) => {
  const searchParams = window.location.search.slice(1);
   
  // 将search参数解析为对象
  let paramsObj:any = {};
  searchParams.split('&').forEach((param) => {
    const [key, value] = param.split('=');
    paramsObj[key] = value;
  });

  let encryptStr = request_id + paramsObj['order'] + md5Key
  let md5 = CryptoJS.MD5(encryptStr).toString()
  console.log('加密前', encryptStr, '加密后', md5)
  return md5
}
